<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.order_sn" clearable placeholder="请输入订单编号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.goods_name" clearable placeholder="请输入商品名称"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.receive_name" clearable placeholder="请输入收货人姓名"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.receive_mobile" clearable placeholder="请输入收货人手机号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model.trim="searchCondition.order_status" placeholder="请选择状态" multiple clearable>
          <el-option v-for="item in selectStatus" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model="searchCondition.express_number" clearable placeholder="请输入快递单号"></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-date-picker v-model="queryDate" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="创建时间" @change="(data: string[]) => changeQueryDate(data, 'start_create_time', 'end_create_time')" end-placeholder="结束时间">
        </el-date-picker>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-date-picker v-model="payTime" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="尾款支付时间" @change="(data: string[]) => changeQueryDate(data, 'start_pay_time', 'end_pay_time')" end-placeholder="结束时间">
        </el-date-picker>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-date-picker v-model="deliveryTime" type="datetimerange" range-separator="至" format="YYYY-MM-DD HH:mm:ss" value-format="X" start-placeholder="发货时间" @change="(data: string[]) => changeQueryDate(data, 'start_send_time', 'end_send_time')" end-placeholder="结束时间">
        </el-date-picker>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="order_sn" label="订单号" align="center"> </el-table-column>
      <el-table-column prop="goods_name" label="商品名称" align="center" :show-overflow-tooltip="true"> </el-table-column>
      <el-table-column prop="order_status_name" label="订单状态" align="center"> </el-table-column>
      <el-table-column prop="express_number" label="快递单号" align="center"> </el-table-column>
      <el-table-column prop="store_name" label="绑定店铺">
        <template #default="scope">
          <div class="ibDraggable">
            <div>{{ scope.row.store_name }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="valuation" label="相关价格">
        <template #default="scope">
          <div class="ibDraggable">
            <div>最高估计：{{ scope.row.valuation }}/元</div>
            <div>商家出价：{{ scope.row.real_price }}/元</div>
            <div>定金：{{ scope.row.deposit }}/元</div>
            <div>尾款：{{ scope.row.balance }}/元</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="receive_name" label="收货信息">
        <template #default="scope">
          <div class="ibDraggable">
            <div>{{ scope.row.receive_name }}</div>
            <div>{{ scope.row.receive_mobile }}</div>
            <div>{{ scope.row.receive_address }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="receive_name" label="收款账户">
        <template #default="scope">
          <div class="ibDraggable">
            <div>支付宝账号：{{ scope.row.alipay_account }}</div>
            <div>姓名：{{ scope.row.alipay_username }}</div>
            <div>转款金额：{{ scope.row.real_price }}/元</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="receive_name" label="相关时间">
        <template #default="scope">
          <div class="ibDraggable">
            <div>预计投资时间：{{ handleVerifyFormatDate(Number(scope.row.create_time)) }}</div>
            <div>尾款支付时间：{{ handleVerifyFormatDate(Number(scope.row.pay_time)) }}</div>
            <div>发货时间：{{ handleVerifyFormatDate(Number(scope.row.send_time)) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <el-button type="primary" link :icon="View" @click="handleViewEdit(scope.row, 'view')">查看</el-button>
            <div v-show="scope.row.status === 'pendingPayment'" v-permission="'cancelOrder'">
              <el-popconfirm placement="top" width="160" title="你确定要取消订单吗?" @confirm="handleCancelOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="Close" type="danger">取消订单</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="['waitingOrder'].includes(scope.row.order_status) && [0, '', null].includes(scope.row.store_id)" v-permission="'accept'">
              <el-popconfirm placement="top" width="160" title="你确定要接单吗?" @confirm="handleAcceptOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="CircleCheck" type="success">接单</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="['waitingReceive'].includes(scope.row.order_status)" v-permission="'confirmOrder'">
              <el-popconfirm placement="top" width="160" title="你确定要收货吗?" @confirm="handleReceiptOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="EditPen" type="success">确认收货</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="['waitingTransfer'].includes(scope.row.order_status)" v-permission="'transfer'">
              <el-popconfirm placement="top" width="160" title="你确定要转账吗?" @confirm="handleTransferMoneyOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="EditPen" type="success">确认转账</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-show="['waitingOrder'].includes(scope.row.order_status) && ![0, '', null].includes(scope.row.store_id)" v-permission="'revoke'">
              <el-popconfirm placement="top" width="160" title="你确定要解除绑定吗?" @confirm="handleRevokeOrder(scope.row.id)">
                <template #reference>
                  <el-button link :icon="EditPen" type="success">解除绑定</el-button>
                </template>
              </el-popconfirm>
            </div>
            <el-button type="success" link :icon="PriceTag" v-permission="'bid'" v-show="['waitingBid'].includes(scope.row.order_status) && ['', null].includes(scope.row.store_id)" @click="handleBidOrder(scope.row)">出价</el-button>
            <el-button type="warning" link :icon="ChatDotSquare" @click="handleOrderRemark(scope.row)">商家备注</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <!-- 出价 -->
    <BidDialog v-model:editVisible="bidVisible" v-model:form="bidForm" @handleSuccess="handleBidSuccess" />
    <!-- 商家备注弹出框 -->
    <RemarkDialog v-model:editVisible="remarkVisible" v-model:form="sellerRemarkForm" @handleSuccess="handleRemarkSuccess" />
  </div>
</template>

<script setup lang="ts">
import BidDialog from "@/components/recoveryManage/recycledGoodsOrderInfo/BidDialog.vue";
import RemarkDialog from "@/components/recoveryManage/recycledGoodsOrderInfo/RemarkDialog.vue";
import { View, Close, CircleCheck, Search, Refresh, ChatDotSquare, EditPen, PriceTag } from "@element-plus/icons-vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { ViewMode, ViewModeFilter } from "@/types/common";
import type { IDictData } from "@/types/dict";
import { useState } from "@/hooks/useState.ts";
import type { IRecycleOrderBid, IRecycleOrderList, IRecycleOrderRemark, ISearchRecycleOrder } from "@/types/recoveryManage/recycleOrder";
import { getRecycleOrderInfo, putRecycleOrderAcceptInfo, putRecycleOrderCancelInfo, putRecycleOrderReceiveInfo, putRecycleOrderRevokeInfo, putRecycleOrderTransferInfo } from "@/utils/api/recycleOrder";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  selectStatus: Array<IDictData>;
}
const { selectStatus } = defineProps<Props>();

const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleToPrint: [ids: number[]];
  handleViewEdit: [id: number, code: ViewModeFilter];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */
const queryDate = ref<Array<string>>([]);
const payTime = ref<Array<string>>([]);
const deliveryTime = ref<Array<string>>([]);
const total = ref(0);

const searchCondition = reactive<ISearchRecycleOrder>({
  goods_name: "",
  order_sn: "",
  receive_name: "",
  receive_mobile: "",
  express_name: "",
  express_number: "",
  start_create_time: "",
  end_create_time: "",
  start_pay_time: "",
  end_pay_time: "",
  start_send_time: "",
  end_send_time: "",
  order_status: [],
  size: 10,
  current: 1
});
const tableList = ref<Array<IRecycleOrderList>>([]);
const sellerRemarkForm = reactive<IRecycleOrderRemark>({
  id: 0,
  admin_note: ""
});
const remarkVisible = ref(false); /* 商家备注弹出框 */
const bidForm = reactive<IRecycleOrderBid>({
  id: 0,
  real_price: ""
});
const bidVisible = ref(false); /* 商家备注弹出框 */
/* 时间更改事件 */
function changeQueryDate(data: string[], startTime: "start_create_time" | "start_pay_time" | "start_send_time", endTime: "end_create_time" | "end_pay_time" | "end_send_time") {
  if (data !== null) {
    searchCondition[startTime] = data[0];
    searchCondition[endTime] = data[1];
  } else {
    searchCondition[startTime] = "";
    searchCondition[endTime] = "";
  }
}
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.goods_name = "";
  searchCondition.order_sn = "";
  searchCondition.receive_name = "";
  searchCondition.receive_mobile = "";
  searchCondition.express_name = "";
  searchCondition.express_number = "";

  searchCondition.start_create_time = "";
  searchCondition.end_create_time = "";
  searchCondition.start_pay_time = "";
  searchCondition.end_pay_time = "";
  searchCondition.start_send_time = "";
  searchCondition.end_send_time = "";
  searchCondition.order_status = [];
  queryDate.value = [];
  payTime.value = [];
  deliveryTime.value = [];
  searchCondition.current = 1;
  searchCondition.size = 10;

  getTableInfo();
}
/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getRecycleOrderInfo<IRecycleOrderList, ISearchRecycleOrder>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IRecycleOrderList, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: IRecycleOrderList) {
  multipleTableRef.value!.toggleRowSelection(row);
}

/* 取消订单 */
function handleCancelOrder(id: number) {
  toggleState(true);
  putRecycleOrderCancelInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, "cancel");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 确认收货 */
function handleAcceptOrder(id: number) {
  toggleState(true);
  putRecycleOrderAcceptInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, "waitingSend");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 确认收货 */
function handleReceiptOrder(id: number) {
  toggleState(true);
  putRecycleOrderReceiveInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, "waitingBid");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 确认转账 */
function handleTransferMoneyOrder(id: number) {
  toggleState(true);
  putRecycleOrderTransferInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);
      /* 修改订单状态 */
      handleChangeOrderStatus(id, "complete");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 解除绑定 */
function handleRevokeOrder(id: number) {
  toggleState(true);
  putRecycleOrderRevokeInfo({ id })
    .then(res => {
      ElMessage.success(res.msg);

      handleChangeOrderStroeInfo(id);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 删除store_namestore_id */
function handleChangeOrderStroeInfo(id: number) {
  const item = tableList.value.find(item => item.id === id);
  if (item) {
    item.store_id = 0;
    item.store_name = "";
  }
}

/* 修改订单状态 */
function handleChangeOrderStatus(id: number, status: string) {
  const item = tableList.value.find(item => item.id === id);
  if (item) {
    item.order_status = status;
    item.order_status_name = selectStatus.find(s => s.dictValue === status)?.dictLabel || "";
  }
}

/* 出价 */
function handleBidOrder(row: IRecycleOrderList) {
  bidForm.id = row.id;
  bidVisible.value = true;
}
/* 出价成功回调 */
function handleBidSuccess() {
  handleChangeOrderStatus(bidForm.id, "waitingConfirm");
  handleChangeRealPrice(bidForm.id, bidForm.real_price);
  bidForm.id = 0;
  bidForm.real_price = "";
}
/* 修改价格 */
function handleChangeRealPrice(id: number, real_price: string) {
  const item = tableList.value.find(item => item.id === id);
  if (item) {
    item.real_price = real_price;
  }
}
/* 商家备注 */
function handleOrderRemark(row: IRecycleOrderList) {
  sellerRemarkForm.id = row.id;
  remarkVisible.value = true;
}
/* 平台备注成功回调 */
function handleRemarkSuccess() {
  remarkVisible.value = false;
}

getTableInfo();
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}
</style>
